
import Taro from "@tarojs/taro";
import { showErrorToast } from "../utils/util";

/**
 * 封封微信的的request
 */
function request (url, data = {}, method = "GET") {
  // console.log(`token:${Taro.getStorageSync('token')}`)
  return new Promise(function (resolve, reject) {
    Taro.request({
      url: url,
      data: data,
      method: method,
      header: {
        Authorized: Taro.getStorageSync("token")
      },
      success: function (res) {
        // console.log(`request===>>${JSON.stringify(res)}`);
        // console.log('请求成功')
        if (res.statusCode == 200) {
          // 请求成功,返回数据
          if (res.data.code === 200) {
            // console.log(res.data);
            resolve(res.data);
          } else {
            if (res.data.code === 401) {
              // console.log('401')
              showErrorToast(res.data.message);
              Taro.redirectTo({
                url: "/pages/login/login"
              });
            } else {
              if (
                res.data.code === 418 &&
                (res.data.message === "微信ID不存在,请先通过账号密码绑定" ||
                  res.data.message === "code 无效")
              ) {
                reject(res.data);
                // console.log("微信ID不存在");
                // Taro.redirectTo({
                //   url: "/pages/login/pwdLogin/pwdLogin"
                // });
              } else {
                console.log("错误提示");
                showErrorToast(res.data.message);
              }
            }
          }
        } else {
          showErrorToast(res.data.message);
        }
      },
      fail: function (err) {
        // console.log(err.status)
        if (err.status == 401) {
          Taro.redirectTo({
            url: "/pages/login/login"
          });
        } else {
          reject(err);
        }
      }
    });
  });
}

request.get = (url, data) => {
  return request(url, data, "GET");
};

request.post = (url, data) => {
  return request(url, data, "POST");
};

export default request;
